# -*- coding:utf-8 -*-
import numpy as np
import datetime

path = '/Users/junming/Desktop/gitlearn/data/data.csv'

# 平均数
def averages():
	# 读取文件，将数据分为收盘价、成交量两组
	c, v = np.loadtxt(path, delimiter = ',', usecols = (6,7),unpack = True)

	# 计算成交量加权平均值（average）
	vwap = np.average(c,weights = v)
	print 'vwap is', vwap

	# 当日成交量加权平均数算法 当日成交总量/成交总数
	csum = np.sum(c)
	vsum = np.sum(v)
	asum = np.sum(c*v)
	print '收盘价总量：%s, 成交总数：%s, 成交量加权平均数（vwap）：%s' %(csum,vsum,asum/vsum)

	# 算术平均值（mean）
	print np.mean(c),np.mean(v),csum/len(c), vsum/len(v)

	# 时间加权平均价格
	t = np.arange(len(c))
	twap = np.average(c,weights = t)
	print 'twap is :', twap

# 中位数
def maxandmin():
	# 获取成交最高价和最低价
	h,l = np.loadtxt(path, delimiter = ',', usecols = (4,5), unpack = True)

	# 最大值 最小值
	print 'highest = %s\nlowest = %s' % (np.max(h), np.min(l))

	# 最大值和最小值之间的差值：max（h）- min（h）= np.ptp()
	print 'Spread high is:',np.ptp(h)
	print 'Spread low is:',np.ptp(l)

# 方差
def simplestats():
	c = np.loadtxt(path, delimiter = ',', usecols = (6,), unpack = True)

	# 计算中位数
	median = np.median(c)

	# 手动计算
	n = len(c)
	sortc = np.sort(c,axis = 0)
	print (sortc[n/2]+sortc[(n-1)/2])/2, median

	# 计算方差
	print '方差：',np.var(c)

	# 手动计算:与平均数差的平方除以总数
	print np.mean((c-np.mean(c))**2)

# 计算收益率
def  yieldrate():
	# 计算收益率
	c = np.loadtxt(path, delimiter = ',', usecols = (6,), unpack = True)

	# diff：c[n]-c(n-1) (n>=1)
	returns = np.diff(c)/c[:-1]

	# std:计算标准差
	print np.std(returns)

	# 对数收益率、简单收益率
	logreturns = np.diff(np.log(c))
	print logreturns,returns

	# 条件返回：where
	print np.where(returns > 0)

	# 年波动率
	# 计算历史波动率(如年波动率或月波动率)时，需要用到对数收益率。
	# 年波动率等于对数收益率的标准差除以其均值，再除以交易日倒数的平方根，通常交易日取252天。
	vave = np.std(logreturns) / np.mean(logreturns)
	year_vave = vave/np.sqrt(1./252.)
	print vave,year_vave

# 日期分析
def datestr3num(s):
	return datetime.datetime.strptime(s, "%d-%m-%Y").date().weekday()

# print datestr3num('28-01-2011')
date,close = np.loadtxt(path, delimiter = ',', usecols = (1,6), converters = {1:datestr3num}, unpack = True)
print date,close

days = np.zeros(5)
print days
















